import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import 'PullRefreshCubit.dart';

class PullRefreshPage extends StatefulWidget {
  const PullRefreshPage({super.key});

  @override
  State<PullRefreshPage> createState() => _PullRefreshPageState();
}

class _PullRefreshPageState extends State<PullRefreshPage> {

  RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async{

    _refreshController.refreshCompleted();
  }

  void _onLoading() async{

    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();

    var pullRefreshCubit = context.read<PullRefreshCubit>();
    pullRefreshCubit.add(PullRefreshInitEvent());
  }

  @override
  Widget build(BuildContext context) {
    var pullRefreshCubit = context.watch<PullRefreshCubit>();
    return Scaffold(
      body: SmartRefresher(
        dragStartBehavior: DragStartBehavior.start,
        enablePullDown: true,
        enablePullUp: true,
        header: ClassicHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus? mode) {
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("pull up load");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("Load Failed!Click retry!");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("release to load more");
            }
            else{
              body = Text("No more Data");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: (){
          pullRefreshCubit.add(PullRefreshLoadOldsEvent(_refreshController));
        },
        onLoading: (){
          pullRefreshCubit.add(PullRefreshLoadNewsEvent(_refreshController));
        },
        child: ListView.builder(
          itemBuilder: (c, i) => Card(child: Center(child: Text(pullRefreshCubit.state.dataList[i]))),
          itemCount: pullRefreshCubit.state.dataList.length,
        ),
      ),
    );
  }
}